var mongoose = require('mongoose');
const News = require('../models/news.model');

// 新增
exports.create = function(req, res, next) {
    const news = new News(req.body);
    news.save().then((data) => {
        res.json(data);
    });
}

exports.update = function(req, res, next) {
    const id = req.params.id;
    News.findByIdAndUpdate(id, { $set: req.body }, { new: false })
        .then(data => {
            res.json(data); // 这里返回的数据是修改之前的数据，不是修改之后的数据
        })
}

exports.remove = function(req, res, next) {
    const id = req.params.id;
    News.findByIdAndDelete(id, (err, data) => {
        res.json(data);
    })
}

exports.list = function(req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    // var limit = req.body.limit ? req.body.limit : 5;
    var rows           = req.body.rows ? req.body.rows : 10;
    var queryCondition = {};                                  //查询条件
    if (req.body.title && req.body.title.trim().length > 0) {
        title          = req.body.title;
        queryCondition = {
            "title": new RegExp(title, 'i')
        }
    }
    //分类Id
    if (req.body.title && req.body.title.trim().length > 0) {
        title          = req.body.title;
        queryCondition = Object.assign(queryCondition, {
            title: title
        })
    }
    News.paginate(queryCondition, { page: +page, limit: +rows }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });

}

//删除多个
exports.removes = function(req, res, next) {
        var ids = req.body.ids.split(',')
        if (ids.length > 0) {
            News.remove({ _id: { $in: ids } }).then(data => {
                res.json({ 'message': 'delete ok', status: 200 })
            })
        }
    }
    //根据id获取单个数据
exports.getData = function(req, res, next) {
    var id = req.params.id;
    News.findById(id).then(data => {
        res.json(data);
    })
}